import http from '../../utils/http'
import { loadingFun } from '../../utils/tools'
import { requestPayment } from '../../utils/wx'
import { showModel, showNotify, showToast, showDialog } from '../../utils/index'
import { getUserInfo } from '../../utils/auth'

Component({
    /**
     * 组件的属性列表
     */
    properties: {
        type: {
            type: String,
            value: 'all'
        },
    },

    /**
     * 组件的初始数据
     */
    data: {
        // 商品列表
        orderList: [],

        status: 'loading',
        queryParams: {
            page: 1,
            limit: 15,
            sortColumns: 'ctime',
            sortType: 'desc',
            memberId: null
        },

        userInfo: null
    },

    observers: {
        'type': function (type) {
            this.getOrderListFun(type)
        }
    },

    /**
     * 组件的方法列表
     */
    methods: {
        /**
         * 请求数据
         * @param {*} queryParams 
         * @returns 
         */
        async getOrderList(queryParams) {
            return await http.get('/api/mall/omsorder/page', queryParams)
        },

        /**
         * 分页加载数据
         * @returns 
         */
        async getOrderListFun(type) {
            let { orderList, queryParams, status } = this.data

            if(type == 'all') {
                queryParams.inStatus = '0,1,2,3,4'
            } else if(type == 'pay') {
                // 待付款, 
                queryParams.inStatus = '0'
            } else if(type == 'delivery') {
                // 待收货
                queryParams.inStatus = '1,2'
            } else if(type == 'finish') {
                // 已完成
                queryParams.inStatus = '3'
            } else if(type == 'close') {
                // 已关闭
                queryParams.inStatus = '4'
            }
            
            // 会员ID
            queryParams.memberId = getUserInfo().id

            // 分页加载数据
            const data = await loadingFun(this.getOrderList, queryParams, orderList, status)
            if (!data) return
            orderList = data.dataList || []

            orderList.forEach(item => item.statusText = this.getOrderStatus(item.status))

            this.setData({ orderList, queryParams: data.queryParams, status: data.status })
        },

        payNow(e) {
            const { APPID, userInfo } = getApp().globalData
            let { id } = e.currentTarget.dataset
            let order = this.getOrderById(id)
            console.log(order);
            
            // 微信订单预支付请求体参数
            const orderPayParams = {
                appid: APPID,
                openid: userInfo.openid,
                outTradeNo: order.orderSn,
                body: '[保美驰]商品支付',
                totalFee: order.payAmount * 100
            }

            // 发起 预支付接口
            http.post(`/api/wx/order/pay/${APPID}/now`, orderPayParams).then(res => {
                if (res.status) {
                    wx.hideLoading()
                    // 发起 微信支付
                    requestPayment(res.data).then(res => {
                        const { errMsg } = res
                        if (errMsg === 'requestPayment:ok') {
                            console.log(res);
                            // 跳转到支付成功页面
                            let pay_result = {
                                orderSn: order.orderSn,
                                payTime: order.utime,
                                payAmount: order.payAmount,
                                payWayText: '微信支付'
                            }
                            wx.reLaunch({
                                url: '/pages/order_pay_result/order_pay_result?data='+JSON.stringify(pay_result)
                            });
                        } else {
                            wx.hideLoading()
                            console.log('订单支付失败[' + errMsg + ']');
                        }
                    }).catch(function(err) {
                        wx.hideLoading()
                        console.log('调起微信支付失败：', err);

                        if (err.errMsg === 'requestPayment:fail cancel') {
                            console.log('用户取消支付');
                        }
                        if (err.errMsg === 'requestPayment:fail no permission') {
                            console.log('title: 未开通支付权限[' + err.errMsg + ']');
                        }
                    })

                } else {
                    wx.hideLoading()
                    console.log('发起微信支付', res.msg);
                }
            })
        },

        /**
         * 会员确认收货
         */
        async comfirmOrder(e) {
            let { confirm } = await showModel({content: '确认收货？'})

            if(confirm){
                const { userInfo } = getApp().globalData
                let { id } = e.currentTarget.dataset
                let res = await http.request('/api/mall/omsorder/memberConfirmReceivePack', {id, memberId: userInfo.id})
                if(res.status) {
                    let { queryParams } = this.data
                    queryParams.page = 1
                    this.setData({status: 'loading', queryParams, orderList: []})
                    this.getOrderListFun(this.data.type)
                }
            }
        },

        /**
         * 申请售后
         * @param {*} e 
         */
        async applyRefund(e) {
            let { id } = e.currentTarget.dataset
            wx.navigateTo({ url: '/pages/apply_refund/apply_refund?orderId='+id})
        },

        /**
         * 根据订单ID获取订单信息
         * @param {*} id 
         * @returns 
         */
        getOrderById(id) {
            let { orderList } = this.data

            let order = orderList.filter(v => v.id == id)
            
            if(order && order.length != 0) {
                return order[0]
            } else {
                return null
            }
        },

        /**
         * 订单状态
         * @param {*} status 
         * @returns 
         */
         getOrderStatus(status) {
            let text = ''
            switch (status) {
                case 0:
                    text = '待支付';
                    break;
                case 1:
                    text = '待发货';
                    break;
                case 2:
                    text = '待收货';
                    break;
                case 3:
                    text = '已完成';
                    break;
                case 4:
                    text = '订单已关闭';
                    break;
            }
            return text
        }
    }
})
